/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fandi.controller;

import com.fandi.model.CustomerModel;
import com.fandi.model.ItemModel;
import com.fandi.model.TransactionDetailOutModel;
import com.fandi.model.TransactionDetailOutTableModel;
import com.fandi.model.TransactionOutModel;
import com.fandi.model.TransactionOutTableModel;
import com.fandi.util.AutoCompletion;
import com.fandi.util.DateFormatterUtil;
import com.fandi.util.Message;
import com.fandi.view.TransFrame;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;

/**
 *
 * @author fandiak
 */
public class TransactionController {
    private ItemModel itemModel;
    private List<TransactionDetailOutModel> listOutItems;
    private CustomerModel customerModel;
    private TransactionOutModel transactionOutModel;
    
    private TransactionOutTableModel transOutTableModel;
    private TransactionDetailOutTableModel transDetailOutTableModel;

    private boolean isUpdate;
    private int index;
    
    public TransactionController() {
        listOutItems = new ArrayList<>();
    }
    
    public void setItemModel(ItemModel itemModel) {
        this.itemModel = itemModel;
    }

    public void setCustomerModel(CustomerModel customerModel) {
        this.customerModel = customerModel;
    }

    public void setTransactionOutModel(TransactionOutModel transactionOutModel) {
        this.transactionOutModel = transactionOutModel;
    }

    public void setTransOutTableModel(TransactionOutTableModel transOutTableModel) {
        this.transOutTableModel = transOutTableModel;
    }

    public void setTransDetailOutTableModel(TransactionDetailOutTableModel transDetailOutTableModel) {
        this.transDetailOutTableModel = transDetailOutTableModel;
    }
    
    @SuppressWarnings("unchecked")
    public void populateItems(TransFrame view) {
        try {
            List<ItemModel> model = itemModel.selectAll();
            
            DefaultComboBoxModel cmbModel = new DefaultComboBoxModel();
            
            for (ItemModel itemModel : model) {
                cmbModel.addElement(itemModel);
            }
            
            view.getCmbTransOutItem().removeAllItems();
            view.getCmbTransOutItem().setModel(cmbModel);
            
            AutoCompletion.enable(view.getCmbTransOutItem());
        } catch (SQLException ex) {
            Logger.getLogger(TransactionController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /*
    public void populateCustomers(TransFrame view) {
        try {
            List<CustomerModel> model = customerModel.selectAll();
            
            view.getCmbTransInName().removeAllItems();
            for (CustomerModel customerModel : model) {
                view.getCmbTransInName().addItem(customerModel);
            }
            
            AutoCompletion.enable(view.getCmbTransInName());
        } catch (SQLException ex) {
            Logger.getLogger(TransactionController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    */
    
    public ItemModel getItem(TransFrame view) {
        ItemModel selectedModel = (ItemModel) view.getCmbTransOutItem().getSelectedItem();
        return selectedModel;
    }
    
    /*
    public void getCustomer(TransFrame view) {
        CustomerModel selectedModel = (CustomerModel) view.getCmbTransInName().getSelectedItem();
        if (selectedModel != null) {
            System.out.println(selectedModel.getCode());
        }
    }
    */
    
    public void renderTableTransOut(TransFrame view, boolean isSearch, String strName) {
        List<TransactionOutModel> list = transactionOutModel.selectAll();
        try {
            /*
            if (!isSearch) {
                list = new ArrayList<>();
            } else {
                list = new ArrayList<>();
            }
            */
            
            transOutTableModel.setList(list);
            view.getTbTransOutData().setModel(transOutTableModel);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void renderTableDetailTransOut(TransFrame view, List<TransactionDetailOutModel> list) {
        try {
            if(list != null) {
                transDetailOutTableModel.setList(list);
            }
                    
            view.getTbTransDetailOutData().setModel(transDetailOutTableModel);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void generateTransCode(TransFrame view) {
        Date currDate = new Date();
        String strCurrDate = DateFormatterUtil.formatNow("yyyyMMddhhmmss", currDate);
        
        String transCode = "TR" + strCurrDate;
        view.getTxtTransOutCode().setText(transCode);
    }
    
    public void addOutItem(TransFrame view) {
        ItemModel item = getItem(view);
        
        int qty = (int) view.getTxtTransOutQty().getValue();
        
        TransactionDetailOutModel detailModel = new TransactionDetailOutModel();
        detailModel.setItem(item);
        detailModel.setQty(qty);
        
        int index = 0;
        int oldQty = detailModel.getQty();
        boolean found = false;
        
        for (TransactionDetailOutModel transactionDetailOutModel : listOutItems) {
            if (item.getCode().equals(transactionDetailOutModel.getItem().getCode())) {
                index = listOutItems.indexOf(transactionDetailOutModel);
                oldQty = transactionDetailOutModel.getQty();
                found = true;
            }
        }
        
        if (found) {
            listOutItems.remove(index);
            detailModel.setQty(oldQty + qty);
        }
        
        listOutItems.add(detailModel);        
        
        renderTableDetailTransOut(view, listOutItems);
        
        view.getTxtTransOutQty().setValue(1);
    }
    
    public void removeOutItem(TransFrame view) {
        int selectedIndex = view.getTbTransDetailOutData().getSelectedRow();
        
        int index = 0;
        boolean found = false;
        
        String itemCode = (String) view.getTbTransDetailOutData().getValueAt(selectedIndex, 0);
        
        for (TransactionDetailOutModel transactionDetailOutModel : listOutItems) {
            if (itemCode.equals(transactionDetailOutModel.getItem().getCode())) {
                index = listOutItems.indexOf(transactionDetailOutModel);
                found = true;
            }
        }
        
        if (found) {
            listOutItems.remove(index);
        }       
        
        renderTableDetailTransOut(view, listOutItems);
        
        view.getBtnTransOutRemoveItem().setEnabled(false);
    }
    
    public String getTotalItems() {
        System.out.println(transactionOutModel.count());
        String count = String.valueOf(transactionOutModel.count());
        return count;
    }
    
    public void setTotalRecords(TransFrame view) {
        view.getLblTransOutTotalRecords().setText(getTotalItems());
    }
    
    public void reset(TransFrame view) {
        transactionOutModel.reset();
        isUpdate = false;
        view.getBtnTransOutRemoveItem().setEnabled(false);
        view.getTbTransOutData().clearSelection();
    }
    
    /*
    * Untuk kebutuhan insert data transaksi utama.
    */
    public int insert(TransFrame view) {
        
        int returnVal = 0;
        
        String transCode    = view.getTxtTransOutCode().getText();
        String destination  = view.getTxtTransOutDestination().getText();
        String note         = view.getTxtTransOutDesc().getText();
        
        if (transCode.equals("")) {
            Message.showMessage("Transaction Code is required!", "Error", Message.ERROR);
        } else if (destination.equals("")) {
            Message.showMessage("Transaction Destination is required!", "Error", Message.ERROR);
        } else {
            
            transactionOutModel.setTransCode(transCode);
            transactionOutModel.setDescription(note);
            transactionOutModel.setDestination(destination);
            transactionOutModel.setLastUpd(new Date());
            transactionOutModel.setTransDate(new Date());
            
            returnVal = transactionOutModel.insert();
            
            renderTableTransOut(view, false, null);
            
            transactionOutModel.reset();
            setTotalRecords(view);
            generateTransCode(view);
        }
        
        return returnVal;
    }
    
    public void insertDetail(TransFrame view) {
        
        int retVal = insert(view);
        
        System.out.println("Return ID : "  + retVal);
        
    }
    
    public void delete() {
        
    }
}
